package cn.yh.nft.turbo.chain.domain.service;

import cn.yh.nft.turbo.api.chain.constant.ChainType;
import cn.yh.nft.turbo.base.utils.BeanNameUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 链服务工厂
 * @ClassName: ChainServiceFactory
 * @Author: 草莓爱上啵啵
 */

@Service
public class ChainServiceFactory {

    /**
     * 自动注入ChainService的Map，用于管理不同的链式服务
     */
    @Autowired
    private final Map<String, ChainService> chainServiceMap = new ConcurrentHashMap<String, ChainService>();


    /**
     * 根据链类型获取相应的链服务
     *
     * @param chainType 链类型，用于确定具体的链服务实现
     * @return 对应链类型的链服务实现
     * @throws UnsupportedOperationException 如果找不到对应的链服务实现，抛出此异常
     */
    public ChainService get(ChainType chainType){
        //根据链类型名称生成对应的Bean名称，用于后续从map中获取服务实例
        String beanName = BeanNameUtils.getBeanName(chainType.name(), "ChainService");

        //组装出beanName, 并从map中获取相对应的bean
        ChainService service = chainServiceMap.get(beanName);

        //如果找到对应的服务实例，则返回该实例
        if (service != null){
            return service;
        } else {
            //如果未找到对应的服务实例，抛出异常，指示不支持的操作
            throw new UnsupportedOperationException(
                    "No ChainService Found With chainType : " + chainType);
        }
    }
}
